package code.example.base.util.concurrent.lock.barrier;

import code.example.tool.LogFactory;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class BarrierByAQS implements Barrier {

    Sync sync = null ;
    public BarrierByAQS(int count){
        sync = new Sync(count);
    }
    class Sync extends AbstractQueuedSynchronizer{
        public Sync(int count){
            this.setState(count);
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            for(;;){
                int state = this.getState();
                int newState = state - arg;
                LogFactory.getLog().info(Thread.currentThread().getName()+" state:"+state+",newState"+newState);
                if(state <0 || this.compareAndSetState(state,newState)){
                    if(newState <0){
                        return true;
                    }else{
                        return false;
                    }
                }
            }

        }



        @Override
        protected int tryAcquireShared(int arg) {
            int state = this.getState();
            if(state <=0){
                this.releaseShared(1);
            }else{

            }
            return state<=0?1:-1;

        }
    }
    @Override
    public void await() {
        sync.releaseShared(1);
        sync.acquireShared(1);
    }
}
